const fs = require('fs');
const path = require('path');

const dirName = path.join(process.env['HOME'], './.gravity-s3');
const configFile = path.join(dirName, 's3config.json');

export const createConfigFile = () => {
  if (!fs.existsSync(dirName)) {
    fs.mkdirSync(dirName);
  }

  if (!fs.existsSync(configFile)) {
    let content = '{}';
    fs.writeFile(configFile, content, error => {
      if (error) {
        return console.log(error);
      }
      console.log('config file created');
    });
  } else {
    console.log('config file already exist');
  }
};

export const readConfig = callback => {
  fs.readFile(configFile, (err, content) => {
    const currentConfig = JSON.parse(content);
    callback(currentConfig);
  });
};

export const readCurrentS3Creadential = callback => {
  createConfigFile();
  fs.readFile(configFile, (err, content) => {
    const currentConfig = JSON.parse(content);
    let currentAccount;
    if (currentConfig.currentId) {
      const index = currentConfig.accounts.findIndex(
        account => account.id == currentConfig.currentId
      );
      currentAccount = currentConfig.accounts[index];
    } else {
      currentAccount = null;
    }
    console.log('readCurrentS3Creadential');
    console.log(currentConfig);

    callback(currentAccount);
  });
};

export const updateConfig = (newAddAccount, callback) => {
  readConfig(currentConfig => {
    let accounts = currentConfig.accounts || [];
    let oldIndex = accounts.findIndex(
      account => account.id == newAddAccount.id
    );
    if (oldIndex > -1) {
      accounts[oldIndex] = { ...newAddAccount };
    } else {
      newAddAccount.id = Date.now();
      accounts.push({ ...newAddAccount });
    }
    const newConfig = Object.assign({}, currentConfig, {
      accounts
    });

    _updateConfigFile(newConfig, callback);
  });
};

export const updateSelectAccountId = (account, callback) => {
  readConfig(currentConfig => {
    const newConfig = {
      ...currentConfig,
      currentId: account.id
    };
    _updateConfigFile(newConfig, callback);
  });
};

function _updateConfigFile(newConfig, callback) {
  fs.writeFile(configFile, JSON.stringify(newConfig), error => {
    if (error) {
      return console.log(error);
    }
    console.log('config file updated');
    callback();
  });
}

export const deleteAccount = (targetAccount, callback) => {
  readConfig(currentConfig => {
    let accounts = currentConfig.accounts || [];
    let oldIndex = accounts.findIndex(
      account => account.id === targetAccount.id
    );
    if (oldIndex > -1) {
      accounts.splice(oldIndex, 1);
      const newConfig = Object.assign({}, currentConfig, {
        accounts
      });

      fs.writeFile(configFile, JSON.stringify(newConfig), error => {
        if (error) {
          return console.log(error);
        }
        callback();
      });
    }
  });
};
